package com.xfcode.ai.platform;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import lombok.AllArgsConstructor;
import lombok.NonNull;

import java.io.File;
import java.util.List;

@AllArgsConstructor
public class PlatformClient {

    private String apiKey;
    private String filesUrl;
    private String modelsUrl;
    private String estimateTokenCountUrl;


    public  String getModelList() {
        return getCommonRequest(modelsUrl)
                .execute()
                .body();
    }

    public  String uploadFile(@NonNull File file) {
        return getCommonRequest(filesUrl)
                .method(Method.POST)
                .header("purpose", "file-extract")
                .form("file", file)
                .execute()
                .body();
    }
    public  String uploadFile( byte[] fileBytes, String fileName) {
        return getCommonRequest(filesUrl)
                .method(Method.POST)
                .header("purpose", "file-extract")
                .form("file", fileBytes,fileName)
                .execute()
                .body();
    }

    public  String getFileList() {
        return getCommonRequest(filesUrl)
                .execute()
                .body();
    }

    public  String deleteFile(@NonNull String fileId) {
        return getCommonRequest(filesUrl + "/" + fileId)
                .method(Method.DELETE)
                .execute()
                .body();
    }

    public  String getFileDetail(@NonNull String fileId) {
        return getCommonRequest(filesUrl + "/" + fileId)
                .execute()
                .body();
    }

    public  String getFileContent(@NonNull String fileId) {
        return getCommonRequest(filesUrl + "/" + fileId + "/content")
                .execute()
                .body();
    }

    public  String estimateTokenCount(@NonNull String model, @NonNull List<Message> messages) {
        String requestBody = new JSONObject()
                .putOpt("model", model)
                .putOpt("messages", messages)
                .toString();
        return getCommonRequest(estimateTokenCountUrl)
                .method(Method.POST)
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(requestBody)
                .execute()
                .body();
    }

    private  HttpRequest getCommonRequest(@NonNull String url) {
        return HttpRequest.of(url).header(Header.AUTHORIZATION, "Bearer " + apiKey);
    }

}
